import { ScrollView, View } from '@tarojs/components';
import cssModule from './index.module.scss';
import { useState } from 'react';

/**
 * @description 列表容器
 * @author Shawn
 */

// 接收父组件参数
interface DefaultPageProps {
  showText?: boolean;
  height?: string;
  hasMore?: boolean;
  isMore?: boolean;
  isDataLoaded?: boolean;
  childrenNode?: React.ReactNode;
  onPullDownRefresh?: () => Promise<void> | void;
  onScrollToLower?: () => Promise<void> | void;
}

export default function ScrollList({
  height,
  showText = true,
  hasMore = true,
  isMore = true,
  isDataLoaded = true,
  childrenNode,
  onPullDownRefresh,
  onScrollToLower,
}: DefaultPageProps) {

  const [action, setAction] = useState<'none' | 'refresh' | 'loading'>('none');

  const handleScrollToLower = async () => {
    if (action === 'loading') return
    setAction('loading');
    if (onScrollToLower) {
      await onScrollToLower();
      setAction('none');
    }
  }

  const handlePullDownRefresh = async () => {
    setAction('refresh');
    if (onPullDownRefresh) {
      await onPullDownRefresh();
    }
  }

  return (
    <ScrollView
      className={cssModule.container}
      scrollY
      enable-flex
      refresherEnabled={false}
      onScrollToLower={handleScrollToLower}
      onScrollToUpper={handlePullDownRefresh}
      lowerThreshold={100}
      upperThreshold={-50}
      style={height ? { height } : undefined}
    >
      {isDataLoaded && action === 'refresh' && <View className={cssModule.noMore}>正在加载...</View>}
      <View className={cssModule.scrollListItem}>{childrenNode}</View>
      {isDataLoaded && action === 'loading' && <View className={cssModule.noMore}>正在加载...</View>}
      {showText && !hasMore && !isDataLoaded && isMore && <View className={cssModule.noMore}>没有更多数据了...</View>}
    </ScrollView>
  );
}
